package ink.xiaobaibai.controller.free;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ink.xiaobaibai.annotation.InsidePublicResources;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.common.FreeClientUserStatus;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.entity.AdminUser;
import ink.xiaobaibai.entity.ClientUser;
import ink.xiaobaibai.entity.FreeClientUser;
import ink.xiaobaibai.entity.FreeOzoneDevice;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.service.IClientUserService;
import ink.xiaobaibai.service.IFreeClientUserService;
import ink.xiaobaibai.service.IFreeOzoneDeviceService;
import ink.xiaobaibai.serviceOxy.ISmsService;
import ink.xiaobaibai.units.MySecurity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 免费机器控制人员
 * @author: 小白白
 * @create: 2021-07-25
 **/

@RestController
@Api(tags = "免费机器控制人员")
@RequestMapping("/free/clientUser")
@CrossOrigin
@InsidePublicResources
public class FreeClientUserController {

    @Autowired
    private IFreeClientUserService freeClientUserService;

    @Autowired
    private IFreeOzoneDeviceService freeOzoneDeviceService;

    @Autowired
    private IClientUserService clientUserService;

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private ISmsService smsService;

    @GetMapping("/list")
    @ApiOperation("查看当前控制人员列表/ clientUserId和deviceId和address(机器的安装地址) 为搜索条件,选传")
    public ResponseFormat list(@RequestParam("pageNum") Integer pageNum,
                               @RequestParam("pageSize") Integer pageSize,
                               @RequestParam(value = "clientUserId", required = false) Integer clientUserId,
                               @RequestParam(value = "deviceId", required = false) Integer deviceId,
                               @RequestParam(value = "address", required = false) String address) {

        Integer userId = MySecurity.getUserId();
        String role = MySecurity.getRole();
        List<Integer> ids;
        // 主Query
        QueryWrapper<FreeClientUser> masterQ = new QueryWrapper<>();
        QueryWrapper<FreeOzoneDevice> q2 = new QueryWrapper<>();
        q2.select("id");
        if (address != null) {
            q2.eq("address", address);
        }

        if (role.equals(MyRole.DISTRIBUTOR) && !MySecurity.isPower(MyRole.POWER_FREE)) {
            // 只能查看自己个人的机器对应的用户
            q2.eq("admin_user_id", userId);
            ids = this.freeOzoneDeviceService.list(q2).stream().map(FreeOzoneDevice::getId).collect(Collectors.toList());
            if (deviceId != null) {
                if (!ids.contains(deviceId)) {
                    return ResponseFormat.fail("只能查询自己的机器");
                } else {
                    masterQ.eq("device_id", deviceId);
                }
            } else {
                if (ids.size() != 0) {
                    masterQ.in("device_id", ids);
                } else {
                    // 没有就为空,那么就什么也搜不到,就象征性的搜索到一个
                    masterQ.eq("id", 1);
                }
            }
        } else if (role.equals(MyRole.AGENT) && !MySecurity.isPower(MyRole.POWER_FREE)) {
            // 只能查看自己部门的机器对应的用户
            q2.eq("dep_id", this.adminUserService.getDepId(userId));
            ids = this.freeOzoneDeviceService.list(q2).stream().map(FreeOzoneDevice::getId).collect(Collectors.toList());
            if (ids.size() != 0) {
                masterQ.in("device_id", ids);
            } else {
                // 没有就为空,那么就什么也搜不到,就象征性的搜索到一个
                masterQ.eq("id", 1);
            }
            if (deviceId != null) {
                if (!ids.contains(deviceId)) {
                    return ResponseFormat.fail("只能查询自己部门的机器");
                } else {
                    masterQ.eq("device_id", deviceId);
                }
            } else {
                if (ids.size() != 0) {
                    masterQ.in("device_id", ids);
                } else {
                    // 没有就为空,那么就什么也搜不到,就象征性的搜索到一个
                    masterQ.eq("id", 1);
                }
            }
        } else {
            // 管理员或者权限员
            if (deviceId != null) {
                q2.eq("id", deviceId);
            }
            if (address != null || deviceId != null) {
                // 去检查, null 对 mybatisPlus 有什么影响? eq null 那么就是等于 mysql 中的 eq null, 将会一个都查不到
                ids = this.freeOzoneDeviceService.list(q2).stream().map(FreeOzoneDevice::getId).collect(Collectors.toList());
                if (ids.size() != 0) {
                    masterQ.in("device_id", ids);
                } else {
                    // 没有就为空,那么就什么也搜不到,就象征性的搜索到一个
                    masterQ.eq("id", 1);
                }
            }
        }

        if (clientUserId != null) {
            masterQ.eq("client_user_id", clientUserId);
        }
        Page<FreeClientUser> page = this.freeClientUserService.page(new Page<>(pageNum, pageSize), masterQ);
        return ResponseFormat.success(page);
    }

    @PostMapping("/add")
    @ApiOperation("添加酒店机器控制人员(开启第一流程,后续还需要 [经理和管理] 进行审核后,才真正生效)")
    public ResponseFormat add(@RequestBody @Validated FreeClientUser freeClientUser) {
        Integer clientUserId = freeClientUser.getClientUserId();
        QueryWrapper<ClientUser> q1 = new QueryWrapper<>();
        q1.eq("id", clientUserId);
        if (this.clientUserService.count(q1) == 0) {
            return ResponseFormat.fail("小程序用户不存在");
        }
        Integer deviceId = freeClientUser.getDeviceId();
        QueryWrapper<FreeOzoneDevice> q2 = new QueryWrapper<>();
        q2.select("admin_user_id");
        q2.eq("id", deviceId);
        FreeOzoneDevice freeOzoneDevice = this.freeOzoneDeviceService.getOne(q2);
        if (freeOzoneDevice == null) {
            return ResponseFormat.fail("当前机器不存在");
        }
        if (!MySecurity.isPower(MyRole.POWER_FREE) && !freeOzoneDevice.getAdminUserId().equals(MySecurity.getUserId())) {
            return ResponseFormat.fail("绑定机器非自己机器,不可对其进行操作");
        }
        QueryWrapper<FreeClientUser> q3 = new QueryWrapper<>();
        q3.eq("device_id", freeClientUser.getDeviceId());
        q3.eq("client_user_id", freeClientUser.getClientUserId());
        if (this.freeClientUserService.count(q3) != 0) {
            return ResponseFormat.fail("已经为当前用户设置当前机器了,无法重复添加,请前往修改");
        }
        String role = MySecurity.getRole();
        if (MySecurity.isPower(MyRole.POWER_FREE)) {
            freeClientUser.setStatus(FreeClientUserStatus.OK.getStatus());
        } else if (role.equals(MyRole.AGENT)) {
            freeClientUser.setStatus(FreeClientUserStatus.ADMIN.getStatus());
            this.smsService.oaSms(1, "酒店人员添加");
        } else {
            freeClientUser.setStatus(FreeClientUserStatus.AGENT.getStatus());
            AdminUser adminUser = this.adminUserService.getAgentIdByDepId(this.adminUserService.getDepId(MySecurity.getUserId()));
            this.smsService.oaSms(adminUser.getId(), "酒店人员添加");
        }
        this.freeClientUserService.save(freeClientUser);
        return ResponseFormat.success();
    }

    @PutMapping("/update")
    @ApiOperation("修改用户[可以在列表加一个修改,用此接口进行修改] (注:当状态已经完成的时候,就只能经理及其以上级别角色去修改)")
    public ResponseFormat update(@RequestBody @Validated FreeClientUser freeClientUser) {
        String role = MySecurity.getRole();
        if (freeClientUser.getId() == null) {
            return ResponseFormat.fail("请携带id");
        }
        FreeClientUser dbFreeClientUser = this.freeClientUserService.getById(freeClientUser.getId());
        if (dbFreeClientUser.getStatus().equals(FreeClientUserStatus.OK.getStatus())) {
            if (role.equals(MyRole.DISTRIBUTOR)) {
                return ResponseFormat.fail("当前状态已完成,需要联系经理以上人员修改");
            }
        }
        Integer clientUserId = freeClientUser.getClientUserId();
        QueryWrapper<ClientUser> q1 = new QueryWrapper<>();
        q1.eq("id", clientUserId);
        if (this.clientUserService.count(q1) == 0) {
            return ResponseFormat.fail("小程序用户不存在");
        }
        Integer deviceId = freeClientUser.getDeviceId();
        QueryWrapper<FreeOzoneDevice> q2 = new QueryWrapper<>();
        q2.eq("id", deviceId);
        if (this.freeOzoneDeviceService.count(q2) == 0) {
            return ResponseFormat.fail("当前机器不存在");
        }
        QueryWrapper<FreeClientUser> q3 = new QueryWrapper<>();
        q3.eq("device_id", freeClientUser.getDeviceId());
        q3.eq("client_user_id", freeClientUser.getClientUserId());
        if (this.freeClientUserService.count(q3) > 1) {
            return ResponseFormat.fail("已经为当前用户设置当前机器了,无法重复添加,请前往修改");
        }
        freeClientUser.setStatus(null);
        this.freeClientUserService.updateById(freeClientUser);
        return ResponseFormat.success();
    }

    @GetMapping("/pendingList")
    @ApiOperation("查看自己的待处理流程")
    public ResponseFormat pendingList() {
        String role = MySecurity.getRole();
        Integer userId = MySecurity.getUserId();
        QueryWrapper<FreeClientUser> masterQ = new QueryWrapper<>();
        if (role.equals(MyRole.DISTRIBUTOR)) {
            QueryWrapper<FreeOzoneDevice> q2 = new QueryWrapper<>();
            q2.select("id");
            q2.eq("admin_user_id", userId);
            List<Integer> ids = this.freeOzoneDeviceService.list(q2).stream().map(FreeOzoneDevice::getId).collect(Collectors.toList());
            if (ids.size() != 0) {
                masterQ.in("device_id", ids);
            } else {
                return ResponseFormat.success(new ArrayList<>());
            }
        } else if (role.equals(MyRole.AGENT)) {
            QueryWrapper<FreeOzoneDevice> q2 = new QueryWrapper<>();
            q2.select("id");
            q2.eq("dep_id", this.adminUserService.getDepId(userId));
            List<Integer> ids = this.freeOzoneDeviceService.list(q2).stream().map(FreeOzoneDevice::getId).collect(Collectors.toList());
            if (ids.size() != 0) {
                masterQ.in("device_id", ids);
            } else {
                return ResponseFormat.success(new ArrayList<>());
            }
            masterQ.eq("status", FreeClientUserStatus.AGENT.getStatus());
        } else {
            // 管理员
            masterQ.eq("status", FreeClientUserStatus.ADMIN.getStatus());
        }
        List<FreeClientUser> list = this.freeClientUserService.list(masterQ);
        return ResponseFormat.success(list);
    }

    @GetMapping("/item/{id}")
    @ApiOperation("根据id查看clientUser的详细信息 || 返回 授权表 机器表 小程序客户表")
    public ResponseFormat item(@PathVariable("id") Integer id) {
        FreeClientUser freeClientUser = this.freeClientUserService.getById(id);
        Integer deviceId = freeClientUser.getDeviceId();
        Integer clientUserId = freeClientUser.getClientUserId();
        FreeOzoneDevice freeOzoneDevice = this.freeOzoneDeviceService.getById(deviceId);
        QueryWrapper<ClientUser> q1 = new QueryWrapper<>();
        q1.select("user_nickname", "user_image", "user_phone");
        q1.eq("id", clientUserId);
        ClientUser clientUser = this.clientUserService.getOne(q1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("freeClientUser", freeClientUser);
        jsonObject.put("freeOzoneDevice", freeOzoneDevice);
        jsonObject.put("clientUser", clientUser);
        return ResponseFormat.success(jsonObject);
    }

    @GetMapping("/approval-agent/{id}")
    @ApiOperation("经理批准接口,传入批准的id")
    public ResponseFormat approvalAgent(@PathVariable("id") Integer id) {
        Integer userId = MySecurity.getUserId();
        String role = MySecurity.getRole();
        if (!role.equals(MyRole.AGENT)) {
            return ResponseFormat.fail("非经理,不可批准");
        }
        QueryWrapper<FreeClientUser> q0 = new QueryWrapper<>();
        q0.select("status", "device_id");
        q0.eq("id", id);
        FreeClientUser freeClientUser = this.freeClientUserService.getOne(q0);
        if (!freeClientUser.getStatus().equals(FreeClientUserStatus.AGENT.getStatus())) {
            return ResponseFormat.fail("操作失败,当前状态为:" + freeClientUser.getStatus());
        }
        Integer deviceId = freeClientUser.getDeviceId();
        QueryWrapper<FreeOzoneDevice> q1 = new QueryWrapper<>();
        q1.eq("id", deviceId);
        q1.eq("dep_id", this.adminUserService.getDepId(userId));
        if (this.freeOzoneDeviceService.count(q1) == 0) {
            return ResponseFormat.fail("非自己管理的人员");
        }
        UpdateWrapper<FreeClientUser> u1 = new UpdateWrapper<>();
        u1.set("status", FreeClientUserStatus.ADMIN.getStatus());
        u1.eq("id", id);
        this.freeClientUserService.update(u1);
        this.smsService.oaSms(1, "酒店人员添加");
        return ResponseFormat.success();
    }

    @GetMapping("/approval-admin/{id}")
    @ApiOperation("管理员批准接口,传入批准的id")
    @ResourcesRoleMapping(resourceName = "管理员批准酒店人员", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_FREE})
    public ResponseFormat approvalAdmin(@PathVariable("id") Integer id) {
        String role = MySecurity.getRole();
        if (!role.equals(MyRole.ADMIN)) {
            return ResponseFormat.fail("非管理员,不可批准");
        }
        QueryWrapper<FreeClientUser> q0 = new QueryWrapper<>();
        q0.select("status", "device_id");
        q0.eq("id", id);
        FreeClientUser freeClientUser = this.freeClientUserService.getOne(q0);
        if (!freeClientUser.getStatus().equals(FreeClientUserStatus.ADMIN.getStatus())) {
            return ResponseFormat.fail("操作失败,当前状态为:" + freeClientUser.getStatus());
        }
        UpdateWrapper<FreeClientUser> u1 = new UpdateWrapper<>();
        u1.set("status", FreeClientUserStatus.OK.getStatus());
        u1.eq("id", id);
        this.freeClientUserService.update(u1);
        return ResponseFormat.success();
    }

    /**
     * 管理删除当前申请
     */
    @DeleteMapping("/delete")
    @ApiOperation("管理员删除当前申请")
    @ResourcesRoleMapping(resourceName = "管理员删除酒店人员", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_FREE})
    public ResponseFormat delete(@RequestParam("id") Integer id) {
        this.freeClientUserService.removeById(id);
        return ResponseFormat.success();
    }


}
